/*
 * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.sonyericsson.example2;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;

public class FavouritesExtensionActivity extends Activity {

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Retrieve the URI from the intent, this is a URI to a MediaStore audio
        // file
        Intent intent = getIntent();
        Uri trackUri = intent.getData();
        
        //Get the id of the Favourites playlist
        int playlistid = idForplaylist("Favourites");
        if(playlistid != -1) {
                
	        //Get the id of the track being played
	        int trackId = getIdForTrack(trackUri);
	        
	        //Add the id to the favourites playlist
	        addToPlaylist(trackId, playlistid);
	        
	        Toast.makeText(this, "Added to Favourites", Toast.LENGTH_SHORT).show();
        }
        else {
        	Toast.makeText(this, "Favourites playlist does not exist", Toast.LENGTH_SHORT).show();
        }
        
        super.finish();

    }
	
    public void addToPlaylist(long trackId, long playlistid) {

            ContentResolver resolver = getContentResolver();
            
            // need to determine the number of items currently in the playlist,
            // so the play_order field can be maintained.
            String[] cols = new String[] {
                    "count(*)"
            };
            Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
            Cursor cur = resolver.query(uri, cols, null, null, null);
            cur.moveToFirst();
            int base = cur.getInt(0);
            cur.close();
            
            ContentValues value = new ContentValues();
            value.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base));
            value.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, trackId);

            resolver.insert(uri, value);          
    }
	
	/***
	 * Gets the Id for the given track URI
	 * @param trackUri
	 * @return
	 */
	private int getIdForTrack(Uri trackUri) {
		
        Cursor trackCursor = getContentResolver().query(
                trackUri,
                new String[] { MediaStore.Audio.Media._ID }, null, null, null);
        int id = -1;
        if (trackCursor != null) {
        	trackCursor.moveToFirst();
            if (!trackCursor.isAfterLast()) {
                id = trackCursor.getInt(0);
            }
        }
        trackCursor.close();
        return id;
	}


	/***
	 * Gets the id of the favourites playlist
	 * @param name
	 * @return
	 */
    private int idForplaylist(String name) {
    	  	
        Cursor playlistCursor = getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Audio.Playlists._ID },
                MediaStore.Audio.Playlists.NAME + "=?",
                new String[] { name },
                MediaStore.Audio.Playlists.NAME);
        int id = -1;
        if (playlistCursor != null) {
            playlistCursor.moveToFirst();
            if (!playlistCursor.isAfterLast()) {
                id = playlistCursor.getInt(0);
            }
        }
        playlistCursor.close();
        return id;
    }
	       
}
